﻿using JSLCloud.App.Mes.Models;
using JSLCloud.App.Mes.Models.TPMUser;
using JSLCloud.App.Mes.Service;
using JSLCloud.DBModel;
using JSLCloud.Framework;
using JSLCloud.Models;
using JSLCloud.Utilities.WebApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace JSLCloud.App.Mes.Controllers
{
    /// <summary>
    /// T_Users Controller
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TUsersController : ControllerBase
    {
        private readonly ITUsersService _service;
        
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public TUsersController(ITUsersService service)
        {
            _service = service;
        }
        
        /// <summary>
        /// 获取T_Users数据表数据
        /// </summary>
        /// <param name="requestObject">返回响应结果</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseObject<List<UserQueryModel>>>  Get(string requestObject)
        {
            var request = JsonConvert.DeserializeObject<RequestObject<TUsersModel>>(requestObject);
            return await _service.GetAsync(request);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public async Task<ResponseObject<List<dynamic>>> GetUsers()
        {
            var result = await _service.GetUsersAsync();
            Dictionary<int, dynamic> dic = new Dictionary<int, dynamic>();
            foreach(var item in result.Data)
            {
                var o = new
                {
                    value = item.DeptId +1000000,//DeptId可能和UserId重复，导致前端显示可能错误
                    label = item.DeptName,
                    children = result.Data.Where(p => p.DeptId == item.DeptId).Select(p => new
                    {
                        value = p.ID,
                        label = p.UserName
                    })
                };
                if (!dic.ContainsKey(o.value))
                {
                    dic.Add(o.value, o);
                }
            }
            return ResponseUtil<List<dynamic>>.SuccessResult(dic.Values.ToList());
        }

        /// <summary>
        /// 获取权限信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public async Task<ResponseObject<int,UserInfo>> GetInfo()
        {
            var userId = TokenManager.GetUserIDbyToken(Request.Headers);
            if(userId < 0)
            {
                return ResponseUtil<int, UserInfo>.FailResult(new RequestObject<int>(), null, "用户ID信息错误");
            }
            return await _service.GetInfoAsync(userId);
        }

        /// <summary>
        /// 获取权限信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("[action]")]
        public async Task<ResponseObject<int>> GetUserDept()
        {
            var userId = TokenManager.GetUserIDbyToken(Request.Headers);
            if (userId < 0)
            {
                return ResponseUtil<int>.FailResult(-1, "用户ID信息错误");
            }
            return await _service.GetUserDeptAsync(userId);
        }


        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        [HttpPost]
        [HttpOptions]
        [Route("[action]")]
        [AllowAnonymous]
        public async Task<ResponseObject<TPMUserAccountAddModel, LoginResult>> LoginPost(RequestObject<TPMUserAccountAddModel> requestObject)
        {
            var result= await _service.LoginAsync(requestObject);
            return result;
        }

        /// <summary>
        /// 移动端登录系统
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        [HttpPost]
        [HttpOptions]
        [Route("[action]")]
        [AllowAnonymous]
        public async Task<ResponseObject<LoginResult>> MobileLogin(RequestObject<TPMUserAccountAddModel> requestObject)
        {
            return await _service.MobileLoginAsync(requestObject);
        }

        /// <summary>
        /// 新增T_Users数据表数据，支持批量新增
        /// </summary>
        /// <param name="requestObject">返回响应结果</param>
        [HttpPost]
        [HttpOptions]
        public async Task<ResponseObject<TUsersModel,bool>> Post(RequestObject<TUsersModel> requestObject)
        {
            return await _service.PostAsync(requestObject);
        }

        /// <summary>
        /// 修改T_Users数据表数据，支持批量修改
        /// </summary>
        /// <param name="requestObject">返回响应结果</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResponseObject<TUsersModel,bool>> Put(RequestObject<TUsersModel> requestObject)
        {
            return await _service.PutAsync(requestObject);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("[action]")]
        public async Task<ResponseObject<bool>> ModifyPwd(RequestObject<ModifyPwdModel> requestObject)
        {
            var userId = TokenManager.GetCurentUserbyToken(Request.Headers).UserID;
            requestObject.PostData.ID = userId;
            return await _service.ModifyPwdAsync(requestObject);
        }

        /// <summary>
        /// 删除T_Users数据表数据
        /// </summary>
        /// <param name="requestObject">返回响应结果</param>
        [HttpDelete]
        public async Task<ResponseObject<TUsersModel,bool>> Delete(RequestObject<TUsersModel> requestObject)
        {
            return await _service.DeleteAsync(requestObject); 
        }
        
        /// <summary>
        /// 删除T_Users数据表数据，通过主表主键删除主从数据
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        [HttpDelete("ById")]
        public async Task<ResponseObject<int,bool>> Delete(RequestObject<int> requestObject)
        {
            return await _service.DeleteAsync(requestObject);
        }

        /// <summary>
        /// 删除T_Users数据表数据，通过主表主键删除主从数据，批量删除
        /// </summary>
        /// <param name="requestObject"></param>
        /// <returns></returns>
        [HttpDelete("ByIds")]
        public async Task<ResponseObject<int[], bool>> Delete(RequestObject<int[]> requestObject)
        {
            return await _service.DeleteAsync(requestObject);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HttpOptions]
        [Route("[action]")]
        public async Task<ResponseObject<bool>> LogOut()
        {
            var curent = TokenManager.GetCurentUserbyToken(Request.Headers);
            return await _service.LogoutAsync(curent);
        }

        [HttpGet]
        [Route("[action]")]
        public string GetFileToken()
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:8080/user/login?username=18173219235&password=jj716511");
            req.Method = "GET";
            var wr = req.GetResponse();
            var resStream = wr.GetResponseStream();
            var reader = new StreamReader(resStream, Encoding.UTF8);
            var responseContent = reader.ReadToEnd().ToString();
            dynamic jsonObject = JsonConvert.DeserializeObject(responseContent);
            return jsonObject.data.token.ToString();
        }
    }
}
